package fun.easycode.webterminal.adapter.api;

import fun.easycode.webterminal.common.contract.PageDTO;
import fun.easycode.webterminal.common.contract.R;
import fun.easycode.webterminal.service.ScriptTemplateService;
import fun.easycode.webterminal.service.cmd.ScriptTemplateExecCmd;
import fun.easycode.webterminal.service.cmd.ScriptTemplatePageQry;
import fun.easycode.webterminal.service.cmd.ScriptTemplateSaveCmd;
import fun.easycode.webterminal.service.dto.ScriptTemplateDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Tag(name = "脚本模板")
@RestController
@RequestMapping("/api/script-template")
@CrossOrigin
public class ScriptTemplateApi {

    private final ScriptTemplateService scriptTemplateService;
    private final Map<String, SseEmitter> emitterMap = new ConcurrentHashMap<>();

    @Autowired
    public ScriptTemplateApi(ScriptTemplateService scriptTemplateService) {
        this.scriptTemplateService = scriptTemplateService;
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询脚本模板")
    public R<PageDTO<ScriptTemplateDTO>> page(ScriptTemplatePageQry cmd) {
        return scriptTemplateService.page(cmd);
    }

    @PostMapping("/save")
    @Operation(summary = "保存脚本模板(新建/编辑)")
    public R<String> save(@RequestBody ScriptTemplateSaveCmd cmd) {
        return scriptTemplateService.save(cmd);
    }

    @PostMapping("/delete")
    @Operation(summary = "删除脚本模板")
    public R<String> delete(@RequestParam String id) {
        return scriptTemplateService.delete(id);
    }

    @GetMapping("/get-by-id")
    @Operation(summary = "根据id查询脚本模板")
    public R<ScriptTemplateDTO> getById(@RequestParam String id) {
        return scriptTemplateService.getById(id);
    }

    @PostMapping("/exec")
    @Operation(summary = "执行脚本模板")
    public SseEmitter exec(@RequestBody ScriptTemplateExecCmd cmd) {

        // 设置默认超时时间为0，表示永不超时
        SseEmitter emitter = emitterMap.computeIfAbsent(cmd.getId(), k -> new SseEmitter(0L));

        scriptTemplateService.exec(cmd, emitter);

        emitter.onCompletion(() -> emitterMap.remove(cmd.getId()));

        return emitter;
    }
}
